package com.hqyj.webSocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/payServer/{n}")
@Component
public class PaySocketServer {
    //记录当前会话
    private static CopyOnWriteArraySet<Session> SessionSet = new
            CopyOnWriteArraySet<Session>();
    //用订单编号作为建名，记录当前会话
    private static HashMap<String,Session> map = new HashMap<>();
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("n") String num) throws IOException {
        //记录当前会话
        SessionSet.add(session);
        map.put(num,session);
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session, @PathParam("n") String num) {
        //异常当前会话
        SessionSet.remove(session);
        map.remove(num);

    }

    /**
     * 向当前会话发送消息
     * @param message 信息
     * @throws IOException
     */
    public static void SendMessage(String message,String num) throws IOException {
        //获取所有会话
        Iterator<Session> iterator = SessionSet.iterator();

        while(iterator.hasNext()){
            Session session = iterator.next();
            //找到当前会话，向当前会话对应的客户端发送信息
            if(map.get(num).equals(session)){
                session.getBasicRemote().sendText(message);
            }

        }
    }


}
